<?php
/**
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2019/8/2
 * Time: 17:39
 */

namespace app\home\controller;

use app\common\model\User as umodel;
use think\Db;
use think\Exception;
use think\Url;

class Rent extends Common
{

    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 校验交易密码是否正确
     */
    public function checkPwd()
    {
        $pwd = input('pwd');
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        if(encrypt_user_password($pwd) == $userinfo['sepasswd']){
            //密码验证通过
            $this->ajaxSuccess('验证码通过');
        }else{
            $this->ajaxError('密码错误');
        }
    }

    /**
     * 预约记录
     */
    public function apply()
    {
        $this->templateTitle("预约记录");
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $set_return = umodel::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session('tips', $set_return['msg']);
            $this->redirect("User/index");
        }
        /*先读取几条*/
        $map['uid'] = $userinfo['id'];
        $list = Db::name('apply')->where($map)->order('id desc')->limit(8)->select();
        $this->assign('list', $list);
        return $this->fetch("apply");
    }

    /*
     * 预约记录加载更多
     * */
    public function ajaxmoreapply()
    {
        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 8;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;
        $map['uid'] = session("user_id");
        $list = Db::name('apply')->where($map)->order('id desc')->limit($limit_first, $limit_end)->select();
        //echo M()->getlastsql();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
                $list[$k]['delpoint'] = intval($v['delpoint']);
            }
            $ary = $list;
        } else {
            $ary = [];
        }
        echo json_encode($ary);
    }

    /*
     * 转让记录
     * */
    public function transfer()
    {
        $this->templateTitle("转让记录");
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $map['buyuid'] = $uid;//我买的单子，别人买了卖给我
        $set_return = umodel::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session('tips', $set_return['msg']);
            $this->redirect("User/index");
        }

        //将未读订单改成已读订单
        $datasave['isread'] = 2;
        $saledata['buyuid'] = $uid;//我卖的订单
        $saledata['xs'] = 2;
        $now_date_str = date('Y-m-d');
        $saledata['cansaletime'] = array('<=', strtotime($now_date_str));
        $salenoread = Db::name(config('db_order_table'))->where($saledata)->update($datasave);
        //echo db ()->getlastsql();exit;


        /*转让记录 1待转让  2转让中  3已完成  4申诉*/
        $types = input('types', 1);
        if ($types == 1) {
            $type = 1;
            $map['peiduistatus'] = 1;
        } else if ($types == 2) {
            $type = intval($types);
            $map['peiduistatus'] = 2;
            $map['paystatus'] = array('neq', 2);
        } else if ($types == 3) {
            $type = intval($types);
            $map['peiduistatus'] = 2;
            $map['paystatus'] = 2;
        } else {
            $type = intval($types);
            $map['paystatus'] = 3;
            $u = Url::build('Rent/transfer', 'types=3', 'html', true);
            $u = base64_encode($u);
            $this->redirect('User/appeal', array('u' => $u));
        }
        $this->assign('types', $type);
        $map['xs'] = 2;
        $map['cansaletime'] = array('<=', strtotime($now_date_str));
        $list = Db::name(config('db_order_table'))->where($map)->order('id desc')->limit(3)->select();
        //echo db()->getlastsql();exit;
        $this->assign('list', $list);
        return $this->fetch("transfer");
    }
    /*
     * 交易订单  复制的上面的转让记录
     * */
    public function order()
    {
        $type = input('type', 1);
        $user_id = session("user_id");
        if(request()->isAjax()){
            $page = input('page');
            $page_size = input('page_size');
            $m = \db('trade_order');
            if($type == 1){
                $m->where('user_id', $user_id);
            }
            if($type == 2){
                $m->where('sell_user_id', $user_id);
            }
            if($type == 3){
                $m->where('status', 'in', [2,3]);
                $m->where("user_id|sell_user_id", $user_id);
            }
            if($type == 4){
                $m->where('status', 4);
                $m->where("user_id|sell_user_id", $user_id);
            }
            $list = $m->page($page, $page_size)->order('create_time desc')->select();
            foreach ($list as &$item) {
                if($item['status'] == 1){
                    $item['status_text'] = '待出售';
                }
                if($item['status'] == 2){
                    $item['status_text'] = '待支付';
                }
                if($item['status'] == 3){
                    $item['status_text'] = '待确认';
                }
                if($item['status'] == 4){
                    $item['status_text'] = '确认完成';
                }
                $item['url'] = \url('Rent/orderDetails', ['order_id'=>$item['id']]);
            }
            unset($item);
            $this->ajaxSuccess('请求成功', $list);
        }
        $this->assign('types', $type);
        return $this->fetch("order");
    }

    /*
     * ajax读取转让记录
     * */
    public function ajaxmorerenttransfer()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 3;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;
        $map['buyuid'] = $uid;//我买的单子，别人买了卖给我
        $types = input('types', 1);
        /*转让记录 1待转让  2转让中  3已完成  4申诉*/
        if (empty($types) || $types == 1) {
            $type = 1;
            $map['peiduistatus'] = 1;
        } else if ($types == 2) {
            $type = intval($types);
            $map['peiduistatus'] = 2;
            $map['paystatus'] = array('neq', 2);
        } else if ($types == 3) {
            $type = intval($types);
            $map['peiduistatus'] = 2;
            $map['paystatus'] = 2;
        } else {
            $type = intval($types);
            $map['paystatus'] = 3;
        }
        $this->assign('types', $type);
        $map['xs'] = 2;
        $now_date_str = date('Y-m-d');
        $map['cansaletime'] = array('<=', strtotime($now_date_str));


        $list = Db::name(config('db_order_table'))->where($map)->order('id desc')->limit($limit_first, $limit_end)->select();
        if (!empty($list)) {
            $ary = $list;
            foreach ($ary as $k => $v) {
                $ary[$k]['ctime2'] = $v['ctime'];
                $ary[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
                $ary[$k]['peiduitime2'] = date('Y-m-d H:i:s', $v['peiduitime']);
                $ary[$k]['peiduitime3'] = ($v['peiduitime'] + config('pay_limittime') * 60);
                $ary[$k]['recive_time'] = ($v['paytime'] + config('pay_limittime') * 60);
                $ary[$k]['timestamps'] = time();
            }
        } else {
            $ary = [];
        }
        echo json_encode($ary);
    }

    /*
     * 转让记录详情
     *
     * */
    public function transfercon()
    {
        $this->templateTitle("转让记录_详情");
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $id = intval($_GET['id']);
        $orderinfo = Db::name(config('db_order_table'))->where("buyuid='" . $uid . "' and id='" . $id . "'")->find();
        if (empty($id) || empty($orderinfo)) {
            session('tips', '订单不存在或已支付！');
        }
        $this->assign('buyid', $orderinfo);
        $this->assign('get_man', $userinfo);
        /*获取对方信息*/
        $payman = userallinfo($orderinfo['peiduiuid']);
        $this->assign('payman', $payman);
        return $this->fetch("transfercon");
    }
    /*
     * 订单详情 复制的
     *
     * */
    public function orderDetails()
    {
        $this->templateTitle("订单详情");
        $order_id = input('order_id');
        $order = \db('trade_order')->where('id', $order_id)->find();
        $get_man = \db('user')->where('id', $order['sell_user_id'])->find();
        $pay_man = \db('user')->where('id', $order['user_id'])->find();
        $order['pay_type_text'] = $order['pay_type'] == 0?'未支付':($order['pay_type'] == 1?'微信支付':'支付宝支付');
        $this->assign('order', $order);
        $this->assign('get_man', $get_man);
        $this->assign('payman', $pay_man);
        $this->assign('user_id', session("user_id"));
        return $this->fetch("order_details");
    }

    /**
     * 支付交易订单
     */
    public function payTradeOrder()
    {
        $order_id = input('id');
        $pay_type = input('paytype');
        $img_url = input('upload_geturl');
        $order = \db('trade_order')->where('id', $order_id)->where('status', 2)->find();
        if(empty($order)){
            $this->ajaxError('订单状态错误');
        }
        $update_data = [
            "pay_time"=>now_datetime(),
            "pay_img"=>$img_url,
            "pay_type"=>$pay_type,
            "status"=>3
        ];
        $res = \db('trade_order')->where('id', $order_id)->update($update_data);
        if(!empty($res)){
            $this->ajaxSuccess('提交成功');
        }else{
            $this->ajaxError('提交失败，请刷新后重试');
        }
    }

    /**
     * 交易中心，订单确认收款
     */
    public function sureOrder()
    {
        $order_id = input('order_id');
        $order = \db('trade_order')->where('id', $order_id)->where('status', 3)->find();
        if(empty($order)){
            $this->ajaxError('订单状态异常');
        }

        try {
            \db()->startTrans();;
            $update_data = [
                'status'=>4,
                'sure_time'=>now_datetime()
            ];
            $res = \db('trade_order')->where('id', $order_id)->update($update_data);
            if(empty($res)){
                throw new Exception('操作失败，请刷新后重试');
            }else{
                $insert_data = [
                    "uid"=>$order['user_id'],
                    "isadd"=>1,
                    "nums"=>$order['num'],
                    'fromuid'=>0,
                    "ctime"=>now_datetime(),
                    "info"=>"求购SCB获得"
                ];
                \db('mybot')->insert($insert_data);
                \db('user')->where('id', $order['user_id'])->setInc('mybot', $order['num']);
                \db()->commit();
                $this->ajaxSuccess('操作成功');
            }
        }catch (\Exception $e){
            \db()->rollback();
            $this->ajaxError($e->getMessage());
        }

    }

    /*
     * 抢购记录
     *
     *
     */
    public function index()
    {
        $this->templateTitle("抢购记录");
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $map['peiduiuid'] = $uid;//我买的单子，别人买了卖给我

        //将我买到的订单设为已读
        $readdata['myread'] = 2;
        Db::name(config('db_order_table'))->where($map)->update($readdata);

        $set_return = umodel::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session('tips', $set_return['msg']);
            $this->redirect("User/index");
        }
        /*抢购状态 1抢购中  2已抢购  3取消 申诉*/
        $types = input('types', 1);
        if ($types == 1) {
            $type = 1;
            $map['paystatus'] = array('lt', 2);
        } else if ($types == 2) {
            $map['paystatus'] = 2;
            $type = intval($types);
        } else {
            $type = intval($types);
            $map['paystatus'] = 3;
            $u = Url::build('Rent/index', 'types=2', 'html', true);
            $u = base64_encode($u);
            $this->redirect('User/appeal', array('u' => $u));
        }
        $this->assign('types', $type);
        /*读取前五条抢购记录*/
        $list = Db::name(config('db_order_table'))->where($map)->order('id desc')->limit(5)->select();

        foreach ($list as $k => $v) {
            $other = Db::name(config('db_order_table'))->where("peiduiid='" . $v['id'] . "'")->field('title,daynum,earnpercent')->find();
            $list[$k]['title'] = $other['title'];
            $list[$k]['daynum'] = $other['daynum'];
            $list[$k]['earnpercent'] = $other['earnpercent'];
        }
        $this->assign('list', $list);
        return $this->fetch("index");
    }

    /*
     * ajax加载抢购记录
    */
    public function ajaxmorerentindex()
    {
        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 5;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;

        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $map['peiduiuid'] = $uid;//我买的单子，别人买了卖给我
        /*抢购状态 1抢购中  2已抢购  3取消 申诉*/
        $types = input('types', 1);
        if ($types == 1) {
            $type = 1;
            $map['paystatus'] = array('lt', 2);
        } else if ($types == 2) {
            $map['paystatus'] = 2;
            $type = intval($types);
        } else {
            $map['paystatus'] = 3;
            $type = intval($types);
        }
        $list = Db::name(config('db_order_table'))->where($map)->order('id desc')->limit($limit_first, $limit_end)->select();

        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $other = Db::name(config('db_order_table'))->where("peiduiid='" . $v['id'] . "'")->field('title,daynum,earnpercent')->find();
                $list[$k]['title'] = $other['title'];
                $list[$k]['daynum'] = $other['daynum'];
                $list[$k]['earnpercent'] = $other['earnpercent'];
            }
            $ary = $list;
            foreach ($ary as $k => $v) {
                $ary[$k]['ctime2'] = $v['ctime'];
                $ary[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
                $ary[$k]['peiduitime2'] = date('Y-m-d H:i:s', $v['peiduitime']);
                $ary[$k]['peiduitime3'] = ($v['peiduitime'] + config('setting.pay_limit_time') * 60);
                $ary[$k]['recive_time'] = ($v['paytime'] + config('setting.sure_limit_time') * 60);
                $ary[$k]['timestamps'] = time();
            }
        } else {
            $ary = [];
        }
        echo json_encode($ary);
    }

    /*
     * 查看抢购详情
     * */
    public function payrentok()
    {
        $this->templateTitle("抢购记录_详情");
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $oid = intval(input('id'));
        $payid = Db::name(config('db_order_table'))->where("id='" . $oid . "' and peiduiuid='" . $uid . "'")->find();
        //echo '<pre>';print_r($payid);exit;
        if (empty($oid) || empty($payid)) {
            session('tips', '订单不存在或已支付！');
            $this->redirect('Rent/index');
        }
        $buyid = buyidorder($payid['id']);
        if (empty($buyid['id']) && empty($buyid['buyuid'])) {
            if ($payid['paystatus'] == 2) {
                $newurl = url('Rent/index', ['types' => 2]);
            } else {
                $newurl = url('Rent/index', ['types' => 1]);
            }
            $this->error("该订单已失效！", $newurl);
            exit;
        }
        $this->assign('payid', $payid);
        $this->assign('buyid', $buyid);
        /*收款人信息*/
        $get_man = userallinfo($payid['buyuid']);
        $this->assign('get_man', $get_man);

        return $this->fetch("payrentok");

    }

    /*
     * 抢购产品付款
    */
    public function payrent()
    {
        $this->templateTitle("抢购_付款");
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $oid = intval(input('id'));
        $payid = Db::name(config('db_order_table'))->where("id='" . $oid . "' and peiduiuid='" . $uid . "' and paystatus=0")->find();
        if (empty($payid)) {
            session("tips", '无此订单或已支付！');
            $this->redirect("Rent/index");
        } else {
            $peiduitime = ($payid['peiduitime'] + config('setting.pay_limit_time') * 60);
            if ($peiduitime < time()) {
                session("tips", '支付时间已过！');
                $this->redirect("Rent/index");
            }
            $buyid = buyidorder($payid['id']);

            if (empty($buyid['id']) && empty($buyid['buyuid'])) {
                if ($payid['paystatus'] == 2) {
                    $newurl = url('Rent/index', ['types' => 2]);
                } else {
                    $newurl = url('Rent/index', ['types' => 1]);
                }
                $this->error("该订单已失效！", $newurl);
                exit;
            }


            $this->assign('payid', $payid);
            $this->assign('buyid', $buyid);
            /*收款人信息*/
            $get_man = userallinfo($payid['buyuid']);
            $this->assign('get_man', $get_man);
            return $this->fetch("payrent");
        }
    }

    /*
     * 抢购付款 ajax
     * */
    public function dopayrent()
    {
        if (request()->isAjax()) {
            $result = array(
                's' => 0,
                'msg' => '付款成功'
            );
            $id = input('id');
            $uid = session("user_id");
            $payid = Db::name(config('db_order_table'))->where("id='" . $id . "' and peiduiuid='" . $uid . "' and paystatus=0")->find();
            if (empty($payid)) {
                session("tips", '无此订单或已支付！');
                $this->redirect("Rent/index");
            }
            /*开始执行上传信息*/
            $map['id'] = $id;
            $data['paytype'] = trim($_POST['paytype']);
            $data['payimg'] = trim($_POST['upload_geturl']);
            $data['paystatus'] = 1;
            $data['paytime'] = time();
            $s = Db::name(config('db_order_table'))->where('id=' . $id)->update($data);
            if ($s) {
                $result['s'] = 1;
            } else {
                $result['msg'] = "付款失败";
            }
            echo json_encode($result);
            exit();
        }
    }

    /*确认收到款项  xuanfeng 20190625
    * 发放佣金（一级，二级，三级）并添加记录
    * 发放团队奖并添加记录
    * 修改订单状态
    */
    public function suregetmoney()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $id = intval(input('id'));
        $orderinfo = Db::name(config('db_order_table'))->where("buyuid='" . $uid . "' and id='" . $id . "' and paystatus=1")->find();
        if (empty($id) || empty($orderinfo)) {
            session("tips", '无此订单或已支付！');
            $this->redirect("Rent/transfer", ['types' => 3]);
        }
        /*执行确认收款代码*/
        $get_result = sureget($id, $orderinfo);
        if ($get_result == 1) {
            session("tips", '确认收款成功！');
            $this->redirect("Rent/transfer", ['types' => 3]);
        } else {
            session("tips", '系统服务繁忙,请稍后重试');
            $this->redirect("Rent/transfer", ['types' => 3]);
        }

    }
}
